let _Vue;
export default class VueHashRouter {
  static install(Vue) {
    // 实现VueHashRouter插件
    if (VueHashRouter.install.installed) {
      return;
    }
    VueHashRouter.install.installed = true;
    // 缓存Vue
    _Vue = Vue;
    // 在所有的Vue组件挂载router实例
    _Vue.mixin({
      created() {
        // 根Vue组件
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
          this.$options.router.init() // 初始化router实例方法
        }
        console.log(this.$router);
      }
    });
  }
  // 实例化router对象
  constructor(options) {
    this.options = options; // 传递路由规则
    this.routesMap = {}; // 路由与组件映射
    // 当前路由信息
    this.route = _Vue.observable({
      current: this.formatUrl()
    });
  }
  init() {
    this.initRoutesMap();
    this.initEvent();
    this.createComponents();
  }
  initRoutesMap() {
    // 初始化路由映射表
    this.options.routes.forEach(route => {
      this.routesMap[route.path] = route.component;
    });
  }
  initEvent() {
    // 初始化路由事件
    window.addEventListener('hashchange', () => {
      this.route.current = this.formatUrl()
    })
  }
  createComponents() {
    // 创建自带组件
    _Vue.component("router-link", {
      props: {
        to: {
          type: String
        }
      },
      render(h) {
        return h(
          "a",
          {
            attrs: {
              href: `#${this.to}`
            }
          },
          [this.$slots.default]
        );
      },
      methods: {
        handleClick() {
          this.$router.route.current = this.to;
        }
      }
    });
    const self = this;
    _Vue.component("router-view", {
      render(h) {
        // 根据当前路由映射组件
        const component = self.routesMap[self.route.current];
        return h(component);
      }
    });
  }
  formatUrl() {
    return location.hash ? location.hash.substr(1): '/'
  }
}
